package com.wangmeng.book.job;

import com.wangmeng.book.utils.ConstValueUtils;

import java.io.Serializable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * User: 王猛
 * Date: 13-10-1
 */
public class JobExecutorHelper implements Serializable {
    private static ScheduledThreadPoolExecutor executorPool = new ScheduledThreadPoolExecutor(4);
    private static JobExecutorHelper helper = new JobExecutorHelper();
    private ConcurrentHashMap<Integer, Runnable> taskMap = new ConcurrentHashMap<Integer, Runnable>();

    private JobExecutorHelper() {
        init();
    }

    public static JobExecutorHelper getExecutorHelper() {
        return helper;
    }

    public int startJobByType(int jobType, int delay, int period, TimeUnit unit) {
        try {
            Runnable task = null;
            switch (jobType) {
                case ConstValueUtils.JOB_LIST: {
                    task = new UpdateBookListJob();
                    break;
                }
                case ConstValueUtils.JOB_LOAD: {
                    task = new ContentLoadJob();
                    break;
                }
                case ConstValueUtils.JOB_UPDATE: {
                    task = new ContentUpdateJob();
                    break;
                }
                case ConstValueUtils.JOB_PUBLISH: {
                    task = new BookPublishJob();
                    break;
                }
            }
            if (task != null) {
                taskMap.put(jobType, task);
                if (period > 0) {
                    executorPool.scheduleAtFixedRate(task, delay, period, unit);
                } else {
                    executorPool.schedule(task, delay, unit);
                }
            }
        } catch (Exception ex) {
            return ConstValueUtils.CODE_EXCEPTION;
        }
        return ConstValueUtils.CODE_SUCCESS;
    }

    public int stopJobByType(int jobType) {
        try {
            Runnable task = taskMap.remove(jobType);
            if (task != null) {
                executorPool.remove(task);
            }
        } catch (Exception ex) {
            return ConstValueUtils.CODE_EXCEPTION;
        }
        return ConstValueUtils.CODE_SUCCESS;
    }

    public void init() {

    }

    public void close() {
        executorPool.shutdown();
    }
}
